package com.masterclient.app.modules.goods;

import android.Manifest;
import android.os.Build;
import android.os.Environment;
import android.support.annotation.RequiresApi;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.eoner.baselib.utils.toast.ToastUtil;
import com.eoner.baselibrary.utils.NetworkingUtil;
import com.eoner.baselibrary.utils.UIUtils;
import com.eoner.baselibrary.widget.PermissionDialog;
import com.eoner.managerlibrary.router.AroutePath;
import com.masterclient.app.BaseFragment;
import com.masterclient.app.R;
import com.masterclient.app.base.ProgressLoginDialog;
import com.masterclient.app.utils.DownLoadAsyncTasks;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.io.File;
import java.util.ArrayList;
import java.util.Objects;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 作者：Hxm
 * 创建时间：2019/12/24
 * 功能说明：
 */
@Route(path = AroutePath.LOOK_PICTURE_FRAGMENT)
public class LookPictureFragment extends BaseFragment{

    @BindView(R.id.viewPager)
    ViewPager mViewPager;
    @BindView(R.id.tvTitle)
    TextView tvTitle;

    @Autowired(name = "urlList")
    ArrayList<String> urlList;
    @Autowired(name = "position")
    int position;
    @Autowired(name = "product_id")
    String product_id;
    @Autowired(name = "product_name")
    String product_name;


    private RxPermissions rxPermissions;
    private int mPosition;
    private DownLoadAsyncTasks myDownLoadAsyncTask;
    private ProgressLoginDialog progressDialog;

    public static LookPictureFragment newInstance() {
        return new LookPictureFragment();
    }

    @Override
    protected View getRootView(LayoutInflater inflater) {
        hideStatusBar(Objects.requireNonNull(getActivity()).getWindow());
        return inflater.inflate(R.layout.fragment_look_picture, null);
    }

    @Override
    public void onResume() {
        super.onResume();
        hideStatusBar(Objects.requireNonNull(getActivity()).getWindow());
    }

    /**
     * 隐藏状态栏 不更改布局 针对api14以上的版本
     */
    public static void hideStatusBar(Window window) {
        // 全屏展示
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            // 全屏显示，隐藏状态栏和导航栏，拉出状态栏和导航栏显示一会儿后消失。
            window.getDecorView().setSystemUiVisibility(
                    View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                            | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                            | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                            | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                            | View.SYSTEM_UI_FLAG_FULLSCREEN
                            | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
        } else {
            // 全屏显示，隐藏状态栏
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN);
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    protected void initOnlyOnce() {
        super.initOnlyOnce();

        ARouter.getInstance().inject(this);
        rxPermissions = new RxPermissions(Objects.requireNonNull(getActivity()));
        progressDialog = new ProgressLoginDialog(mContext);

        mPosition = position;
        MyPagerAdapter mPagerAdapter = new MyPagerAdapter(urlList, getContext(), () -> getActivity().finish());
        mViewPager.setAdapter(mPagerAdapter);
        mViewPager.setOffscreenPageLimit(2);//设置预加载的数量，这里设置了2,会预加载中心item左边两个Item和右边两个Item
        mViewPager.setCurrentItem(position);
        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                mPosition = position;
                tvTitle.setText((position + 1) + "/" + urlList.size());
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        tvTitle.setText((position + 1) + "/" + urlList.size());
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (null != myDownLoadAsyncTask) {
            myDownLoadAsyncTask.remove(Objects.requireNonNull(getActivity()));
        }
    }

    @OnClick({R.id.rl_back, R.id.tvDownload, R.id.tvDownloadAll})
    void onClick(View view) {
        switch (view.getId()) {
            case R.id.rl_back:
                Objects.requireNonNull(getActivity()).finish();
                break;
            case R.id.tvDownload:
                boolean hasPermissions = rxPermissions.isGranted(Manifest.permission.WRITE_EXTERNAL_STORAGE);
                if (!hasPermissions){
                    new PermissionDialog(getActivity(), "开启相册权限", "保存图片需要获取保存到相册权限，请在下一个页面点击“允许”" ,
                            R.mipmap.icon_permission_storage, () -> {
                        requestPermissions("");
                    }).show();
                }else {
                    saveImage();
                }
                break;
            case R.id.tvDownloadAll:
                boolean hasPermission = rxPermissions.isGranted(Manifest.permission.WRITE_EXTERNAL_STORAGE);
                if (!hasPermission){
                    new PermissionDialog(getActivity(), "开启相册权限", "保存图片需要获取保存到相册权限，请在下一个页面点击“允许”" ,
                            R.mipmap.icon_permission_storage, () -> {
                        requestPermissions("all");
                    }).show();
                }else {
                    downLoadAllPic();
                }
                break;
        }
    }

    private void requestPermissions(String type){
        rxPermissions
                .requestEach(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe(permission -> {
                    if (permission.granted) {
                        if (type.equals("all")){
                            downLoadAllPic();
                        }else {
                            saveImage();
                        }
                    } else if (permission.shouldShowRequestPermissionRationale) {
                    } else {
                        Toast.makeText(getActivity(), "保存文件权限申请失败,无法保存图片", Toast.LENGTH_SHORT).show();
                    }
                });
    }

    private void saveImage(){
        new Thread(() -> {
            File result = UIUtils.saveImageToSdCard(getActivity(), urlList.get(mPosition));
            if (getActivity() != null){
                getActivity().runOnUiThread(() -> {
                    if (result != null) {
                        Toast.makeText(getActivity(), "图片已保存到相册", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(getActivity(), "下载失败，请重新下载", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        }).start();
    }

    private void downLoadAllPic(){
        if (NetworkingUtil.checkNetworking(getActivity())) {
            progressDialog.show();
            progressDialog.setDesc("下载中...");
            String storePath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "flowerc";
            myDownLoadAsyncTask = new DownLoadAsyncTasks(mContext, null, "", storePath, 0, status -> {
                if (status == 0) {
                    progressDialog.dismiss();
                    ToastUtil.showToast("图片已保存到相册");
                } else {
                    progressDialog.dismiss();
                    ToastUtil.showToast("下载失败，请重新下载");
                }
            });
            //执行下载任务
            myDownLoadAsyncTask.execute(urlList.toArray(new String[urlList.size()]));
        } else {
            ToastUtil.showToast("网络连接不可用，请检查当前网络");
        }
    }


}
